// SPDX-FileCopyrightText: 2025 UnionTech Software Technology Co., Ltd.
// SPDX-License-Identifier: MIT
package metrics

import (
        "os"
        "testing"

        "github.com/stretchr/testify/assert"
        "github.com/prometheus/client_golang/prometheus"
)

func TestDescribe(t *testing.T) {
        collector := NewDovecotCollector("", []string{})
        ch := make(chan *prometheus.Desc, 10)

        go func() {
                collector.Describe(ch)
                close(ch)
        }()

        var descs []*prometheus.Desc
        for d := range ch {
                descs = append(descs, d)
        }

        assert.Len(t, descs, 7)
        assert.Contains(t, descs, collector.upDesc)
}

func TestNewDovecotCollector(t *testing.T) {
        tests := []struct {
                name       string
                socketPath string
                scopes     []string
        }{
                {
                        name:       "default collector",
                        socketPath: "/var/run/dovecot/stats",
                        scopes:     []string{"user"},
                },
                {
                        name:       "multiple scopes",
                        socketPath: "/tmp/dovecot.sock",
                        scopes:     []string{"user", "global"},
                },
        }

        for _, tt := range tests {
                t.Run(tt.name, func(t *testing.T) {
                        collector := NewDovecotCollector(tt.socketPath, tt.scopes)

                        assert.NotNil(t, collector)
                        assert.Equal(t, tt.socketPath, collector.socketPath)
                        assert.Equal(t, tt.scopes, collector.scopes)
                        assert.NotNil(t, collector.upDesc)
                        assert.NotNil(t, collector.processCPUDesc)
                })
        }
}

func TestCollectProcessMetrics(t *testing.T) {
        if _, err := os.Stat("/proc/self/stat"); err != nil {
                t.Skip("Skipping process metrics test on non-Linux system")
        }

        collector := NewDovecotCollector("", []string{})
        ch := make(chan prometheus.Metric, 10)

        err := collector.collectProcessMetrics(ch)
        close(ch)

        assert.NoError(t, err)

        var count int
        for range ch {
                count++
        }
        assert.True(t, count > 0, "Should collect at least one process metric")
}
